package eerbaar.v2.app.java2d;

import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import eerbaar.v2.app.core.ISprite;

public class Java2DSpriteStore {

    private static Java2DSpriteStore single = new Java2DSpriteStore();

    public static Java2DSpriteStore get() {
        return single;
    }

    private final Map<String, ISprite> sprites = new HashMap<String, ISprite>();

    private void fail(String message) {
        System.err.println(message);
        System.exit(0);
    }

    public ISprite getSprite(String ref) {

        if (this.sprites.get(ref) != null) {
            return this.sprites.get(ref);
        }

        BufferedImage sourceImage = null;

        try {
            URL url = this.getClass().getClassLoader().getResource(ref);

            if (url == null) {
                fail("Can't find ref: " + ref);
            }

            sourceImage = ImageIO.read(url);
        } catch (IOException e) {
            fail("Failed to load: " + ref);
        }

        GraphicsConfiguration gc = GraphicsEnvironment
                .getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration();
        Image image = gc.createCompatibleImage(sourceImage.getWidth(),
                sourceImage.getHeight(), Transparency.BITMASK);

        image.getGraphics().drawImage(sourceImage, 0, 0, null);

        ISprite sprite = new Java2DSprite(image);
        this.sprites.put(ref, sprite);

        return sprite;
    }
}
